﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Threading;
namespace DataToViz
{
    public delegate void recivecommand(string command);
    public delegate void close();

    public delegate void MyAsyncCallback(object obj);
    public class NetProcess
    {
        public event recivecommand ReciveCommand;

        private TcpListener listen;
        Thread thread;
        public void Start()
        {
            listen = new TcpListener(6666);
            listen.Start();
            thread = new Thread(run);
            thread.IsBackground = true;
            thread.Start();
        }
      private  void run()
        {
            try
            {
                while (true)
                {
                    TcpClient client = listen.AcceptTcpClient();
                    Thread th = new Thread(readMsg);
                    th.IsBackground = true;
                    th.Start(client);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开端口出错:" + ex.Message);
            }
        }
        private void readMsg(object obj)
        {
            TcpClient rClient = (TcpClient)obj;
            NetworkStream stream=rClient.GetStream();
            try
            {
                byte[] recvBytes = new byte[1024];
                string recvStr = "";
                int bytes = stream.Read(recvBytes,0,1024); ;
                    recvStr = Encoding.ASCII.GetString(recvBytes, 0, bytes);
                   ReciveCommand(recvStr);
                   rClient.Close();
            }
            catch 
            {
                rClient.Close();
            }
        }
        private void CreateSubThread(StreamReader reader)
        {
            ParameterizedThreadStart pts = new ParameterizedThreadStart(NewThreadMethod);
            Thread thread = new Thread(pts);
            thread.Start(reader);
          //  Console.WriteLine("开启新线程处理收发消息。。。。。");
        }


        private void NewThreadMethod(object obj)
        {
            StreamReader reader = obj as StreamReader;
            string temp = "";
            while ((temp = reader.ReadLine()) != null)
            {
                //Console.WriteLine(temp);
                if (ReciveCommand != null)
                {
                    Console.WriteLine("收到的消息:" + temp);
                    ReciveCommand(temp);
                }
            }
        }
    }
}
